package com.sikaryofficial.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sikaryofficial.backend.domain.dto.req.information.ArticleAssociateListReq;
import com.sikaryofficial.backend.domain.dto.resp.StoreListDTO;
import com.sikaryofficial.backend.domain.entity.Store;
import com.sikaryofficial.backend.domain.mapping.StoreMapping;
import com.sikaryofficial.backend.mapper.StoreMapper;
import com.sikaryofficial.backend.service.IStoreService;
import com.sikaryofficial.system.api.model.infomation.ArticleAssociateResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 店铺Service业务层处理
 *
 * @author qinjinyuan
 * @date 2023-10-27
 */
@Service
@Slf4j
@SuppressWarnings(value = "unchecked")
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements IStoreService {
    @Autowired
    private StoreMapper storeMapper;

    @Value("${hismk.backend.store.limitCount}")
    private Integer limitQueryStoreCount;

    /**
     * 获取所有商店列表
     *
     * @return 包含所有商店信息的列表
     */
    @Override
    public List<StoreListDTO> getAllStoreList() {
        LambdaQueryWrapper<Store> countQuery = new LambdaQueryWrapper<>();
        countQuery.eq(Store::getDeletedVersion, 0L);
        int storedCount = this.count(countQuery);

        // 限制查询数据量
        List<Store> storeList = new ArrayList<>();
        if (storedCount > limitQueryStoreCount) {
            storedCount = limitQueryStoreCount;
            // 分批查询数据
            int pageSize = 2000;
            int startPage ;
            for (int i = 0; i < storedCount / pageSize; i++) {
                LambdaQueryWrapper<Store> query = new LambdaQueryWrapper<>();
                query.eq(Store::getDeletedVersion, 0L);
                query.orderByDesc(Store::getShopType,Store::getStoreId);
                startPage = i * pageSize;
                // 第startPage条记录开始,每页取 pageSize 记录
                query.last(" limit " + startPage + "," + pageSize);
                storeList.addAll(this.list(query));
            }
        }else{
            storeList.addAll(this.list(new LambdaQueryWrapper<Store>()
                    .eq(Store::getDeletedVersion, 0L)
                    .orderByDesc(Store::getShopType,Store::getStoreId)
            ));
        }
        log.info("共查询到商店信息数量：" + storeList.size());
        return StoreMapping.INSTANCE.coverDtoListToEntity(storeList);
    }

    @Override
    public IPage<ArticleAssociateResp> getStoreList(IPage<ArticleAssociateResp> page, ArticleAssociateListReq req) {
        return null;
    }
}
